import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/base/AbsLifecycleState.dart';
import 'package:photo_frame/dialog/bind_frame_dialog.dart';
import 'package:photo_frame/mixin/auto_hide_loading.dart';
import 'package:photo_frame/net/model/frame_info_model.dart';
import 'package:photo_frame/provider/app_trans_asset_provider.dart';
import 'package:photo_frame/provider/frames_provider.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/app_const.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';

import 'net/http_manager.dart';

class SelectFramePage extends StatefulWidget {
  late final SelectFrameSource source;
  late final num? coverId;
  late final String? content;
  late final bool? timingSwitch;
  late final DateTime? sendDate;

  SelectFramePage(Map<String, dynamic>? args) {
    source = args?["source"] ?? SelectFrameSource.CALENDAR;
    coverId = args?["coverId"];
    content = args?["content"];
    timingSwitch = args?["timingSwitch"];
    sendDate = args?["sendDate"];
  }

  @override
  State<StatefulWidget> createState() => _SelectFrameState();
}

class _SelectFrameState extends AbsLifecycleState<SelectFramePage>
    with AutoHideLoading {
  GlobalKey<RefreshIndicatorState> _refreshIndicatorStateKey = GlobalKey();

  SelectFrameViewModel _vm = SelectFrameViewModel();

  @override
  void onResume() {
    super.onResume();
    if (context.read<FramesViewModel>().frames?.isNotEmpty != true) {
      _refreshIndicatorStateKey.currentState?.show();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffF2F2F2),
      appBar: commonAppBar(
          AppLocalizationsWrapper.instance.unwrap(context).selectFrame,
          actions: [
            CupertinoButton(
              padding: EdgeInsets.zero,
              onPressed: () {
                var frames = context.read<FramesViewModel>().frames;
                if (frames != null && frames.isNotEmpty) {
                  switch (widget.source) {
                    case SelectFrameSource.BENEDICTION:
                      _vm.sendBenediction(context, frames, widget.coverId,
                          widget.content, widget.timingSwitch, widget.sendDate);
                      break;
                    case SelectFrameSource.GALLERY:
                      FrameInfoModel? frame = frames[_vm.selectedIdx];
                      AppAssetTransProvider.provider()
                          .updateTransAssetBuffer("frame", frame);
                      ARouter.instance.pagePush("/selectFrameFolder");
                      break;
                    case SelectFrameSource.CALENDAR:
                      FrameInfoModel? frame = frames[_vm.selectedIdx];
                      ARouter.instance.pagePop(arguments: frame);
                      break;
                    default:
                      ARouter.instance.pagePop(arguments: {
                        "frameId": frames[_vm.selectedIdx].frame_id,
                        "name": frames[_vm.selectedIdx].name
                      });
                      break;
                  }
                }
              },
              child: actionTextWidget(widget.source ==
                      SelectFrameSource.CALENDAR
                  ? AppLocalizationsWrapper.instance.unwrap(context).selectFrame
                  : AppLocalizationsWrapper.instance.unwrap(context).next),
            )
          ]),
      body: ChangeNotifierProvider<SelectFrameViewModel>(
        create: (BuildContext context) => _vm,
        builder: (_, child) => RefreshIndicator(
          key: _refreshIndicatorStateKey,
          onRefresh: () {
            return context.read<FramesViewModel>().fetch().catchError((e) {
              print(e);
              Fluttertoast.showToast(
                  msg: AppLocalizationsWrapper.instance
                      .unwrap(context)
                      .netError);
            });
          },
          child: Selector<FramesViewModel, List<FrameInfoModel>?>(
            builder: (BuildContext context, List<FrameInfoModel>? frames,
                Widget? child) {
              final count = (frames?.length ?? 0) + 1;
              return ListView.separated(
                  itemBuilder: (BuildContext context, int index) {
                    return index == count - 1
                        ? _addFrameWidget()
                        : _frameItemWidget(frames![index], index);
                  },
                  padding: EdgeInsets.symmetric(vertical: 11, horizontal: 15),
                  separatorBuilder: (BuildContext context, int index) =>
                      SizedBox(
                        height: 11,
                      ),
                  itemCount: count);
            },
            selector: (_, vm) => vm.frames,
            shouldRebuild: (n1, n2) => n1 != n2,
          ),
        ),
      ),
    );
  }

  _frameItemWidget(FrameInfoModel frameInfo, int idx) {
    return Consumer<SelectFrameViewModel>(
        builder: (BuildContext context, value, Widget? child) {
      return CupertinoButton(
        padding: EdgeInsets.zero,
        onPressed: () {
          context.read<SelectFrameViewModel>().select(idx);
        },
        child: Container(
          decoration: BoxDecoration(
            color: value.selectedIdx == idx ? Color(0xffF0F5FF) : Colors.white,
            borderRadius: BorderRadius.circular(9),
            border: value.selectedIdx == idx
                ? Border.all(color: Color(0xff3F74EF), width: 1)
                : null,
          ),
          height: 70,
          child: ListTile(
            leading: Image.asset(
                frameInfo.status == 1
                    ? "images/icon_frame_selected.png"
                    : "images/icon_frame_unselected.png",
                width: 58,
                height: 40),
            title: Text(frameInfo.name ?? ""),
            subtitle: Row(
              children: [
                Container(
                  width: 10,
                  height: 10,
                  decoration: BoxDecoration(
                      color: Color(
                          frameInfo.status == 1 ? 0xff3ad953 : 0xffD8D8D8),
                      borderRadius: BorderRadius.circular(5)),
                ),
                SizedBox(
                  width: 8,
                ),
                Text(
                  frameInfo.status == 1
                      ? AppLocalizationsWrapper.instance.unwrap(context)!.online
                      : AppLocalizationsWrapper.instance
                          .unwrap(context)!
                          .offline,
                  style: TextStyle(color: Color(0xff999999), fontSize: 12),
                )
              ],
            ),
            trailing: Image.asset(
              value.selectedIdx == idx
                  ? "images/icon_circle_selected.png"
                  : "images/icon_circle_unselected.png",
              width: 22,
              height: 22,
            ),
          ),
        ),
      );
    });
  }

  _addFrameWidget() {
    return CupertinoButton(
      padding: EdgeInsets.zero,
      onPressed: () {
        _showAddFrameDialog(context).then((_) {
          _refreshIndicatorStateKey.currentState?.show();
        });
      },
      child: Container(
        height: 70,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(9),
          color: Colors.white,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              "images/icon_add_frame.png",
              width: 26,
              height: 21,
            ),
            SizedBox(width: 16),
            Text(
              AppLocalizationsWrapper.instance.unwrap(context)!.addFrame,
              style: TextStyle(color: Color(0xff333333), fontSize: 16),
            )
          ],
        ),
      ),
    );
  }

  Future<void> _showAddFrameDialog(BuildContext context) {
    return showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) => BindFrameDialog());
  }
}

class SelectFrameViewModel extends ChangeNotifier {
  int _selectedIdx = 0;

  int get selectedIdx => _selectedIdx;

  Future<void> sendBenediction(
      BuildContext context,
      List<FrameInfoModel>? frames,
      num? coverId,
      String? content,
      bool? timingSwitch,
      DateTime? sendDate) async {
    if (frames == null || frames.isEmpty) {
      return;
    }
    return EasyLoading.show(
      maskType: EasyLoadingMaskType.black,
    ).then((e) {
      HttpManager.instance.doRequest("/api/wish", parameters: {
        "frame_id": frames[selectedIdx].frame_id,
        "coverId": coverId,
        "content": content,
        "send_date":
            timingSwitch == true ? sendDate!.millisecondsSinceEpoch : null,
      }).then((e) async {
        if (e.isSuccess) {
          ARouter.instance.pagePop();
          Fluttertoast.showToast(
              msg: AppLocalizationsWrapper.instance
                  .unwrap(context)
                  .successfullySent);
        } else {
          Fluttertoast.showToast(msg: e.msg ?? "");
        }
      }).catchError((e) {
        Fluttertoast.showToast(
            msg: AppLocalizationsWrapper.instance.unwrap(context).netError);
      }).whenComplete(() async {
        EasyLoading.dismiss();
      });
    });
  }

  void select(int idx) {
    _selectedIdx = idx;
    notifyListeners();
  }
}
